#!/bin/sh

set -ex

pkgin() {
    if [ "$(id -u)" -eq 0 ] ; then
        command      pkgin "$@"
    else
        command sudo pkgin "$@"
    fi
}

package_name_transform_from_uppm_to_pkgin() {
    case $1 in
        gm4)      printf '%s\n' 'm4'        ;;
        xxd)      printf '%s\n' 'vim'       ;;
        ninja)    printf '%s\n' 'ninja-build';;
        xmake)    printf '%s\n' 'gmake'     ;;
        golang)   printf '%s\n' 'go124'     ;;
        pkgconf)  printf '%s\n' 'pkg-config';;
        xmlutils) printf '%s\n' 'libxml2'   ;;
        xsltproc) printf '%s\n' 'libxslt'   ;;
        trietool) printf '%s\n' 'libdatrie' ;;
        python3)  printf '%s\n' 'python312' ;;
        texinfo)  printf '%s\n' 'gtexinfo'  ;;
        zig@0.10) printf '%s\n' 'zig' ;;
        zig@0.11) printf '%s\n' 'zig' ;;
        zig@0.12) printf '%s\n' 'zig' ;;
        util-linux)
                  printf '%s\n' 'getopt'
                  ;;
        grpc-plugins)
                  printf '%s\n' 'grpc'
                  ;;
        glib-tools)
                  printf '%s\n' 'glib'
                  ;;
        *)        printf '%s\n' "$1"
    esac
}

main() {
    case $1 in
        about)
            pkgin -v
            ;;
        update)
            pkgin -y update
            ;;
        install)
            shift 1
            for UPPM_PACKAGE_NAME in "$@"
            do
                BREW_PACKAGE_NAME="$(package_name_transform_from_uppm_to_pkgin "$UPPM_PACKAGE_NAME")"
                pkgin -y install "$BREW_PACKAGE_NAME"
            done
            ;;
        is-installed)
            shift 1
            BREW_PACKAGE_NAME="$(package_name_transform_from_uppm_to_pkgin "$1")"
            for item in $(pkgin list | cut -d ' ' -f1)
            do
                case $item in
                    "$BREW_PACKAGE_NAME-"*) return 0
                esac
            done
            return 1
            ;;
        info)
            shift 1
            case $2 in
                installed-dir)
                    printf '%s\n' '/usr/pkg'
                    ;;
            esac
            ;;
        *)  pkgin "$@"
    esac
}

main "$@"
